﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using MyGeneration.dOOdads;
using MethodIT.Helper;

using Hr20.DAL;
using Hr20.BLL;
using Hr20.ProcessFlow;

namespace Appraisal.Web.ZB
{
    public partial class ZBAppraisalForm : System.Web.UI.Page
    {
		private const string HTML_SPACE = "&nbsp;";
		private const string ITEM_CTRL_PREID = "KPItem_";

		private string RelationCode
		{
			get
			{
				string sRelationCode = "";
				if(ViewState["RelationCode"] != null)
				{
					sRelationCode = ViewState["RelationCode"].ToString();
				}
				return sRelationCode;
			}
			set
			{
				ViewState["RelationCode"] = value;
			}
		}

		// 不区分 PostBack
		protected void Page_Load(object sender, System.EventArgs e)
		{
            //phTemplate
            btnPrintTop.Attributes.Add("onclick", "excel(phTemplate);");
            //btnPrintTop.Attributes.Add("onclick", "excel(dtable);");
            btnPrintBottom.Attributes.Add("onclick", "excel(phTemplate);");

            int nSubID = HelperURL.GetIntFromUrlString("SubID");
			int nKpID = HelperURL.GetIntFromUrlString("KpID");
            int nUmpID = HelperURL.GetIntFromUrlString("UmpID");
            int nDisplay = HelperURL.GetIntFromUrlString("Display");
            bool Display = nDisplay.Equals(1);

            DisplayRating(nSubID ,nKpID, nUmpID, Display);
		}
 
        // 评分
        private void DisplayRating(int nSubID,int nKpID ,int nUmpID ,bool Display)
		{
            VW_ZB_ItemResult itemResult = new VW_ZB_ItemResult();
            itemResult.Where.KpID.Value = nKpID;
            itemResult.Where.UmpID.Value = nUmpID;
            itemResult.Where.SubID.Value = nSubID;
            itemResult.Query.Load();

            KP_Subject subject = new KP_Subject();
            subject.LoadByPrimaryKey(itemResult.SubID);
            labKpName.Text = itemResult.KpName;
            labSubName.Text = itemResult.SubName;
            labBidderName.Text = subject.Bidder;
            labEndTime.Text = subject.EndDate.ToString();
            labUmpName.Text = itemResult.UmpName;
            
            lbtnSubmit.Enabled = !Display;
            lbtnSubmitBottom.Enabled = !Display;
            lbtnCompute.Enabled = !Display;
            lbtnComputeBottom.Enabled = !Display;
            btnPrintTop.Enabled = Display;
            btnPrintBottom.Enabled = Display;

            phTemplate.Controls.Add(TableController.CreateTable(itemResult, false));


			lbtnSubmit.Attributes.Add(ConstantController.MSG_ALERT_ACTION, ConstantController.MSG_ALERT_SUBMIT_SCRIPT);
			lbtnSubmitBottom.Attributes.Add(ConstantController.MSG_ALERT_ACTION, ConstantController.MSG_ALERT_SUBMIT_SCRIPT);
		}

        // 检验合法性
		private void CheckValid()
		{
            //不能全是10也不能全是1
			bool bIsAll_10 = true;
			bool bIsAll_1 = true;
            bool bIsBetween = true;
            decimal Score = 0 ;
            //double MaxScore = 0;
            //double MinScore = 0;

            int ItemID = 0;
            KP_Template temp = new KP_Template();
            //vld_Template.ErrorMessage = "";

			for(int i=0; i<Request.Form.Count; i++)
			{
				string sKeyName = Request.Form.GetKey(i);
				if(sKeyName.IndexOf(ITEM_CTRL_PREID) >= 0) 
				{
                    sKeyName = sKeyName.Replace(ITEM_CTRL_PREID, "");
                    sKeyName = sKeyName.Split('_')[0];
                    ItemID = HelperDigit.ConvertToInt32(sKeyName);
                    temp.LoadByPrimaryKey(ItemID);
                    //若是数值数据则计算总分
					if ((Request.Form[i] != null) && (temp.Item_Type==0) && temp.Is_Group )
					{
						decimal dCurrentItemScore = HelperCurrency.GetCurrencyDecimal(Request.Form[i]);
                        //bIsAll_10 = (bIsAll_10 && dCurrentItemScore == temp.Max_Score);
                        //bIsAll_1 = (bIsAll_1 && dCurrentItemScore == temp.Min_Score);

                        bIsBetween = (bIsBetween) && (dCurrentItemScore >= temp.Min_Score) && (dCurrentItemScore <= temp.Max_Score);
                        //计算总分
                        //Score += dCurrentItemScore ;
                        //bool bb = (dCurrentItemScore >= temp.Min_Score) && (dCurrentItemScore <= temp.Max_Score);
                        //string s = temp.Is_Group ? "集" : "项";
                        //if (!bb)
                        //{
                        //    vld_Template.ErrorMessage += "评分指标" + s + "--" + temp.Item_Name + "超出评分范围；\n";
                            
                        //}
					}
				}
			}
            //判断不能是满分、不能是最低分、不能超出分值区间
            //vld_Template.IsValid = (!bIsAll_10) && (!bIsAll_1) && (bIsBetween);
            vld_Template.IsValid = bIsBetween;
            //if (!bIsBetween)
            //{
            //    HelperMessage.Message("评分超出有效范围！");
            //}

            //控制评分表最高分、最低分
            //int nEntryID = HelperURL.GetIntFromUrlString("EntryID");
            //VIEW_KP_ENTRY vw = new VIEW_KP_ENTRY();
            //vw.Where.Entry_ID.Value = nEntryID;
            //if (vw.Query.Load())
            //{
            //    KP_Subject_Table st = new KP_Subject_Table();
            //    if (st.LoadByPrimaryKey(vw.SubjectID, vw.KP_ID))
            //    {
            //        vld_100.IsValid = ((Score >= st.MinScore) && (Score <= st.MaxScore));
            //    }
            //}
            
		}

		// 保存结果，bIsSaved = false, 仅计算结果，不保存
		private void DoSave(bool bIsSaved)
		{
            //数据验证
            CheckValid();

            if (!Page.IsValid)
                return;

            Count();

            if (bIsSaved)
            {
                Save();
                HelperMessage.Message("保存成功");
            }
		}

        private void Save()
        {
            int nSubID = HelperURL.GetIntFromUrlString("SubID");
            int nKpID = HelperURL.GetIntFromUrlString("KpID");
            int nUmpID = HelperURL.GetIntFromUrlString("UmpID");

            VW_ZB_ItemResult vw = new VW_ZB_ItemResult();
            vw.Where.KpID.Value = nKpID;
            vw.Where.SubID.Value = nSubID;
            vw.Where.UmpID.Value = nUmpID;
            vw.Query.Load();
            while (!vw.EOF)
            {
                KP_Item_Result ir = new KP_Item_Result();
                ir.LoadByPrimaryKey(vw.ResultID);

                string ctrlID = ITEM_CTRL_PREID + vw.ItemID.ToString() + "_" + vw.TenderID;
                Control ctrl = phTemplate.FindControl(ctrlID);
                if (ctrl != null)
                {
                    TextBox tb = (TextBox)ctrl;
                    if (vw.Item_Type.Equals(0))
                    {
                        ir.Item_Score = HelperCurrency.GetCurrencyDecimal(tb.Text);
                    }
                    else
                    {
                        ir.Item_Text = tb.Text;
                    }
                    ir.Save();
                }

                vw.MoveNext();
            }
            KP_Subject_Employee se = new KP_Subject_Employee();
            se.Where.SID.Value = nSubID;
            se.Query.Load();
            while (!se.EOF)
            {
                DataRow[] items = vw.DefaultView.Table.Select("TenderID=" + se.EmployeeID);
                string sEntryID = items[0][VW_ZB_ItemResult.ColumnNames.EntryID].ToString();
                KP_Entry entry = new KP_Entry();
                if (entry.LoadByPrimaryKey(HelperDigit.ConvertToInt32(sEntryID)))
                {
                    Control ctrlTotal = phTemplate.FindControl("lb_" + ITEM_CTRL_PREID + se.EmployeeID.ToString());
                    if (ctrlTotal != null)
                    {
                        Label lb = (Label)ctrlTotal;
                        entry.Score = HelperCurrency.GetCurrencyDecimal(lb.Text);

                        //entry.Status = 1;
                    }
                }
                entry.Save();

                se.MoveNext();
            }
            //修改评分专家填报状态
            KP_Subject_Table_Ump stu = new KP_Subject_Table_Ump();
            stu.Where.SubjectID.Value = nSubID;
            stu.Where.KpTableID.Value = nKpID;
            stu.Where.UmpID.Value = nUmpID;
            stu.Where.UmpType.Value = 0;
            stu.Query.Load();
            stu.Status = 1;
            stu.Save();
        }

        //计算分数
        private void Count()
        {
            int nSubID = HelperURL.GetIntFromUrlString("SubID");
            int nKpID = HelperURL.GetIntFromUrlString("KpID");
            int nUmpID = HelperURL.GetIntFromUrlString("UmpID");

            KP_Item_Result kpItemResult = new KP_Item_Result();
            KP_Template template = new KP_Template();
            VW_ZB_ItemResult vw = new VW_ZB_ItemResult();
            KP_Subject_Employee se = new KP_Subject_Employee();
            decimal dTotal = 0;

            se.Where.SID.Value = nSubID;
            se.Query.Load();
            //第一层投标人
            while (!se.EOF)
            {
                vw = new VW_ZB_ItemResult();
                vw.Where.KpID.Value = nKpID;
                vw.Where.Is_Group.Value = true;
                vw.Where.SubID.Value = nSubID;
                vw.Where.UmpID.Value = nUmpID;
                vw.Where.TenderID.Value = se.EmployeeID;
                vw.Query.Load();
                //第二层指标集
                while (!vw.EOF)
                {
                    VW_ZB_ItemResult vwItem = new VW_ZB_ItemResult();
                    decimal dGroupTotal = 0;

                    vwItem.Where.KpID.Value = nKpID;
                    vwItem.Where.Is_Group.Value = false;
                    vwItem.Where.SubID.Value = nSubID;
                    vwItem.Where.UmpID.Value = nUmpID;
                    vwItem.Where.ParentID.Value = vw.ItemID;
                    vwItem.Where.TenderID.Value = se.EmployeeID;
                    vwItem.Query.Load();

                    //第三层指标项目
                    while (!vwItem.EOF)
                    {
                        string ctrlID = ITEM_CTRL_PREID + vwItem.ItemID.ToString() + "_" + se.EmployeeID.ToString();
                        Control ctrl = phTemplate.FindControl(ctrlID);
                        if (ctrl != null)
                        {
                            TextBox tb = (TextBox)ctrl;
                            string sResult = tb.Text;
                            decimal d = 0;
                            if (vwItem.Item_Type.Equals(0))
                            {
                                d = HelperCurrency.GetCurrencyDecimal(sResult);
                            }
                            dGroupTotal += d * vwItem.Item_Quotiety;
                        }

                        vwItem.MoveNext();
                    }
                    string ctrlTotalID = ITEM_CTRL_PREID + vw.ItemID.ToString() + "_" + se.EmployeeID.ToString();
                    Control ctrlTotal = phTemplate.FindControl(ctrlTotalID);
                    if (ctrlTotal != null)
                    {
                        TextBox tbTotal = (TextBox)ctrlTotal;
                        tbTotal.Text = dGroupTotal.ToString();
                    }
                    dTotal += dGroupTotal * vw.Item_Quotiety ;

                    vw.MoveNext();
                }
                string lbID = "lb_" + ITEM_CTRL_PREID + se.EmployeeID.ToString();
                Control ctrlLable = phTemplate.FindControl(lbID);
                if (ctrlLable != null)
                {
                    Label lb = (Label)ctrlLable;
                    lb.Text = dTotal.ToString("N2");
                }
                dTotal = 0;

                se.MoveNext();
            }
        }


		private void ShowScore(string nItemID, decimal dScore, bool IsLabel)
		{
			//Control ctrl = phTemplate.FindControl("lb_" + ITEM_CTRL_PREID + nItemID.ToString());
            Control ctrl = phTemplate.FindControl(nItemID);
			if(ctrl != null)
			{
                if (IsLabel)
                {
                    Label lbItemScore = (Label)ctrl;
                    lbItemScore.Text = dScore.ToString("N2");
                }
                else
                {
                    TextBox txtItem = (TextBox)ctrl;
                    txtItem.Text = dScore.ToString("N2");
                }
			}
		}


        protected void lbtnSubmit_Click(object sender, System.EventArgs e)
        {
            DoSave(true);
        }

        protected void lbtnSubmitBottom_Click(object sender, System.EventArgs e)
        {
            DoSave(true);
        }

        protected void lbtnCompute_Click(object sender, System.EventArgs e)
        {
            DoSave(false);
        }

        protected void lbtnComputeBottom_Click(object sender, System.EventArgs e)
        {
            DoSave(false);
        }

    }
}
